/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2021-2022. All rights reserved.
 *
 */
import * as path from 'path';
import { PackageJson } from 'type-fest';

import { BaseModifier } from './base-modifier';

/**
 * 修改指定模块的package.json
 */
export class PackageJsonModifier extends BaseModifier {
  protected jsonObject!: PackageJson;

  constructor(cwd: string, moduleName: string) {
    super(path.resolve(cwd, moduleName, 'oh-package.json5'));
  }

  public updateMainField(mainField: string) {
    this.jsonObject.main = mainField;
    return this;
  }

  public updateDependency(dependency: string, version: string) {
    if (!this.jsonObject.dependencies) {
      this.setDependencies({});
    }
    this.jsonObject.dependencies![dependency] = version;
    return this;
  }

  public setDependencies(dependencies: { [index: string]: string }) {
    this.jsonObject.dependencies = dependencies;
    return this;
  }

  public updateDependencies(dependencies: { [index: string]: string }) {
    this.jsonObject.dependencies = {
      ...this.jsonObject.dependencies,
      ...dependencies
    };
    return this;
  }
}
